<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-form :inline="true" :model="searchData">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="searchData.startDate"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="searchData.endDate"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 图表容器 -->
      <div ref="chartRef" style="width: 100%; height: 400px; margin-top: 20px;"></div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { getPlatformRevenueApi } from "@/api/statistics"
import type { RevenueStatisticsData } from "@/api/statistics/types/statistics"
import * as echarts from "echarts"

defineOptions({
  // 命名当前组件
  name: "PlatformRevenue"
})

const loading = ref<boolean>(false)
const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null

const searchData = reactive({
  startDate: "",
  endDate: ""
})

const revenueData = ref<RevenueStatisticsData[]>([])

/** 查询 */
const handleSearch = () => {
  if (!searchData.startDate || !searchData.endDate) {
    ElMessage.warning("请选择开始日期和结束日期")
    return
  }
  if (searchData.startDate > searchData.endDate) {
    ElMessage.warning("开始日期不能大于结束日期")
    return
  }
  getRevenueData()
}

/** 重置 */
const resetSearch = () => {
  searchData.startDate = ""
  searchData.endDate = ""
  revenueData.value = []
  updateChart()
}

/** 获取营收数据 */
const getRevenueData = async () => {
  loading.value = true
  try {
    const { data } = await getPlatformRevenueApi({
      startDate: searchData.startDate,
      endDate: searchData.endDate
    })
    revenueData.value = data
    updateChart()
  } catch (error) {
    console.error("获取平台营收数据失败:", error)
  } finally {
    loading.value = false
  }
}

/** 初始化图表 */
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    updateChart()
  }
}

/** 更新图表 */
const updateChart = () => {
  if (!chartInstance) return
  
  const dates = revenueData.value.map(item => item.date)
  const revenues = revenueData.value.map(item => item.revenue)
  
  const option = {
    title: {
      text: '平台营收分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>营收: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '营收金额(元)',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [{
      name: '平台营收',
      type: 'line',
      data: revenues,
      smooth: true,
      itemStyle: {
        color: '#E6A23C'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(230, 162, 60, 0.3)'
          }, {
            offset: 1, color: 'rgba(230, 162, 60, 0.1)'
          }]
        }
      }
    }]
  }
  
  chartInstance.setOption(option)
}

/** 窗口大小改变时重新调整图表 */
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  // 设置默认日期范围（最近7天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(endDate.getDate() - 6)
  
  searchData.endDate = endDate.toISOString().split('T')[0]
  searchData.startDate = startDate.toISOString().split('T')[0]
  
  nextTick(() => {
    initChart()
    getRevenueData()
  })
  
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
const cleanup = () => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
}

// Vue 3 的 onUnmounted
import { onUnmounted } from 'vue'
onUnmounted(cleanup)
</script>

<style lang="scss" scoped>
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form {
    margin: 0;
  }
}
</style>